const nodemailer = require('nodemailer');
require('dotenv').config();

// 创建邮件传输器
const transporter = nodemailer.createTransport({
  host: process.env.EMAIL_HOST,
  port: process.env.EMAIL_PORT,
  secure: false, // true for 465, false for other ports
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASS
  }
});

// 验证码存储
const verificationCodes = new Map();

/**
 * 生成6位数字验证码
 */
function generateVerificationCode() {
  return Math.floor(100000 + Math.random() * 900000).toString();
}

/**
 * 发送验证码邮件
 * @param {string} email - 接收邮箱
 * @param {string} type - 验证码类型 (register/reset)
 * @returns {Promise<boolean>} - 发送结果
 */
async function sendVerificationCode(email, type = 'register') {
  try {
    const code = generateVerificationCode();
    const expiresAt = Date.now() + 5 * 60 * 1000; // 5分钟过期
    
    // 打印验证码到控制台
    console.log(`发送验证码: ${code} 到邮箱: ${email} (类型: ${type})`);
    
    // 存储验证码
    verificationCodes.set(email, {
      code,
      type,
      expiresAt,
      attempts: 0
    });
    
    // 邮件内容
    const subject = type === 'register' ? '注册验证码' : '密码重置验证码';
    const html = `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <h2 style="color: #333; text-align: center;">${subject}</h2>
        <div style="background-color: #f9f9f9; padding: 20px; border-radius: 8px; margin: 20px 0;">
          <p style="font-size: 16px; color: #333;">您好！</p>
          <p style="font-size: 16px; color: #333;">
            您正在进行${type === 'register' ? '注册' : '密码重置'}操作，验证码为：
          </p>
          <div style="text-align: center; margin: 20px 0;">
            <span style="font-size: 24px; font-weight: bold; color: #007bff; background-color: #e7f3ff; padding: 10px 20px; border-radius: 4px; letter-spacing: 2px;">
              ${code}
            </span>
          </div>
          <p style="font-size: 14px; color: #666;">
            验证码有效期为5分钟，请及时使用。如果这不是您的操作，请忽略此邮件。
          </p>
        </div>
        <div style="text-align: center; margin-top: 30px;">
          <p style="font-size: 12px; color: #999;">此邮件由系统自动发送，请勿回复</p>
        </div>
      </div>
    `;
    
    // 发送邮件
    const mailOptions = {
      from: process.env.EMAIL_FROM,
      to: email,
      subject: subject,
      html: html
    };
    
    await transporter.sendMail(mailOptions);
    console.log(`验证码邮件已发送到: ${email}`);
    return true;
    
  } catch (error) {
    console.error('发送验证码邮件失败:', error);
    return false;
  }
}

/**
 * 验证验证码
 * @param {string} email - 邮箱
 * @param {string} code - 验证码
 * @param {string} type - 验证码类型
 * @returns {Object} - 验证结果
 */
function verifyCode(email, code, type = 'register') {
  const storedData = verificationCodes.get(email);
  
  if (!storedData) {
    return {
      success: false,
      message: '验证码不存在或已过期'
    };
  }
  
  // 检查验证码类型
  if (storedData.type !== type) {
    return {
      success: false,
      message: '验证码类型不匹配'
    };
  }
  
  // 检查是否过期
  if (Date.now() > storedData.expiresAt) {
    verificationCodes.delete(email);
    return {
      success: false,
      message: '验证码已过期'
    };
  }
  
  // 检查尝试次数
  if (storedData.attempts >= 3) {
    verificationCodes.delete(email);
    return {
      success: false,
      message: '验证码尝试次数过多，请重新获取'
    };
  }
  
  // 验证码错误
  if (storedData.code !== code) {
    storedData.attempts++;
    return {
      success: false,
      message: `验证码错误，还可尝试${3 - storedData.attempts}次`
    };
  }
  
  // 验证成功，删除验证码
  verificationCodes.delete(email);
  return {
    success: true,
    message: '验证码验证成功'
  };
}

/**
 * 清理过期的验证码
 */
function cleanExpiredCodes() {
  const now = Date.now();
  for (const [email, data] of verificationCodes.entries()) {
    if (now > data.expiresAt) {
      verificationCodes.delete(email);
    }
  }
}

// 每分钟清理一次过期验证码
setInterval(cleanExpiredCodes, 60 * 1000);

module.exports = {
  sendVerificationCode,
  verifyCode
};